<template>
  <div id="app">
    <div>
      <audio
        src="http://qiniu.whxgjt.com/dfh2/bg_music.mp3"
        controls="controls"
        preload
        loop
        id="musicfx"
        hidden
      ></audio>

      <div class="operators">
        <img
          src="~@/assets/img/home/btn_push.png"
          @click="playFn"
          v-show="play"
          alt
        />
        <img
          src="~@/assets/img/home/btn_play.png"
          @click="playFn"
          v-show="!play"
          alt
        />
      </div>
    </div>

    <router-view></router-view>
  </div>
</template>

<script>
export default {
  data() {
    return {
      play: false,
    };
  },
  methods: {
    // 提供给开始做题
    startPlay() {
      var audio = document.getElementById("musicfx");
      if (audio !== null) {
        this.play = true;
        audio.play(); //audio.play();// 这个就是播放
      }
    },
    playFn() {
      var audio = document.getElementById("musicfx");
      if (audio !== null) {
        //检测播放是否已暂停.audio.paused 在播放器播放时返回false.
        if (audio.paused) {
          this.play = true;
          audio.play(); //audio.play();// 这个就是播放
        } else {
          this.play = false;
          audio.pause(); // 这个就是暂停
        }
      }
    },
    autoPlay() {
      const _self = this;
      //--创建页面监听，等待微信端页面加载完毕 触发音频播放
      document.addEventListener("DOMContentLoaded", function () {
        function audioAutoPlay() {
          var audio = document.getElementById("musicfx");
          audio.muted = true;
          audio.play();
          _self.play = true;
          audio.muted = false;
          document.addEventListener(
            "WeixinJSBridgeReady",
            function () {
              audio.play();
              _self.play = true;
            },
            false
          );
        }
        audioAutoPlay();
      });
      //--创建触摸监听，当浏览器打开页面时，触摸屏幕触发事件，进行音频播放
      // document.addEventListener("touchstart", function () {
      //   function audioAutoPlay() {
      //     var audio = document.getElementById("musicfx");
      //     audio.play();
      //   }
      //   audioAutoPlay();
      // });
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.autoPlay();
    });
  },
};
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.operators {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 19;
  img {
    height: 30px;
  }
}
</style>
